import {
	getAllMaterialPage,
	type IMaterialInfoResponse,
	type IMaterialListParams
} from '@/api/marterial';
import { MaterialGroup } from '@/components';
import { useRequest } from '@ac/hooks';
import { AppPagination } from '@ac/ui-components';
import { Button, Drawer } from 'antd';
import to from 'await-to-js';
import { memo, useCallback, useEffect, useState } from 'react';
import { useImmer } from 'use-immer';
import SearchForm, { type SearchFormValues } from '../Components/SearchForm';

type MaterialQueryProps = {
	total: number;
	checkVals: string[];
	materials: IMaterialInfoResponse[];
	queryInfo: IMaterialListParams;
};

type ChooseMaterialDialogProps = {
	visible: boolean;
	onCancel: () => void;
	onOk: (values: { materialList: string[] }) => Promise<void> | void;
};

const ChooseMaterialDialog: React.FC<ChooseMaterialDialogProps> = ({ visible, onCancel, onOk }) => {
	const [loading, setLoading] = useState(false);
	const [state, setState] = useImmer<MaterialQueryProps>({
		total: 0,
		checkVals: [],
		materials: [],
		queryInfo: {
			pageNum: 1,
			pageSize: 10,
			titleKey: '',
			tagKey: ''
		}
	});
	const { run: fetchAllMaterialPage } = useRequest(
		useCallback(
			async params => {
				const [_err, res] = await to(getAllMaterialPage(params));
				if (res) {
					setState(state => {
						state.total = res.pageinfo?.pagecount || 0;
						state.materials = res?.result || [];
					});
				}
			},
			[setState]
		)
	);

	useEffect(() => {
		if (visible) {
			fetchAllMaterialPage(state.queryInfo);
		}
	}, [visible, state.queryInfo, fetchAllMaterialPage]);

	// 搜索表单提交处理
	const handleSearch = (values: SearchFormValues) => {
		setState(state => {
			state.queryInfo = { ...state.queryInfo, ...values, pageNum: 1 };
		});
	};

	// 勾选素材change
	const handleChange = useCallback(
		(values: string[]) => {
			setState(state => {
				state.checkVals = values;
			});
		},
		[setState]
	);

	// 分页查询素材列表
	const handlePaginationChange = useCallback(
		(pageNum: number) => {
			setState(state => {
				state.queryInfo = { ...state.queryInfo, pageNum };
			});
		},
		[setState]
	);

	// 提交素材
	const handleSubmit = async () => {
		try {
			setLoading(true);
			await Promise.resolve(onOk({ materialList: state.checkVals }));
		} finally {
			setLoading(false);
		}
	};

	return (
		<Drawer width="75%" title="添加素材" open={visible} onClose={onCancel}>
			<div className="flex flex-col h-full">
				<SearchForm className="flex-row-reverse" onSearch={handleSearch}>
					<Button
						onClick={handleSubmit}
						disabled={!state.checkVals.length}
						loading={loading}
						type="primary">
						提交
					</Button>
				</SearchForm>
				<div className="bg-[rgba(0,0,0,.04)] p-10 rounded-4 flex-1 h-0 w-full overflow-auto">
					<MaterialGroup
						value={state.checkVals}
						onChange={handleChange}
						materials={state.materials}
						showDelete={false}></MaterialGroup>
				</div>
				{state.total > 0 && (
					<AppPagination
						current={state.queryInfo.pageNum}
						pageSize={state.queryInfo.pageSize}
						total={state.total}
						onChange={handlePaginationChange}
					/>
				)}
			</div>
		</Drawer>
	);
};

export default memo(ChooseMaterialDialog);
